﻿using Microsoft.Extensions.DependencyInjection;
using RQX.Common.Web.Config;
using RQX.Common.Web.Core.Entity;
using RQX.Common.Web.Core.Pagger;
using RQX.Common.Web.Tools;
using System;
using System.Linq;
using System.Linq.Expressions;

namespace RQX.Common.Web.Core.Repository.DbContext
{
    public static class DbContextExtension
    {
        public static void AddDbContext(this IServiceCollection services)
        {
            var sqlConnectionStr = AppConfigurtaion.GetConfigValue($"{GlobalConfig.DB_SectionName}:{GlobalConfig.DB_ApolloConnectionName}");
            services.AddDbContext<BaseDbContext>(option => option.UseSqlServer(sqlConnectionStr));
            services.AddDbContext<CommonDbContext>(option => option.UseSqlServer(sqlConnectionStr));
        }
        /// <summary>
        /// whereif条件过滤
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entities"></param>
        /// <param name="isRun"></param>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public static IQueryable<TEntity> WhereIf<TEntity>(this IQueryable<TEntity> entities, bool isRun, Expression<Func<TEntity, bool>> predicate)
        {
            if (isRun)
            {
                return entities.Where(predicate);
            }
            else
            {
                return entities;
            }
        }

        /// <summary>
        /// 排序
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entities"></param>
        /// <param name="pagger"></param>
        /// <returns></returns>
        public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> entities, IPagger pagger)
            where TEntity : BaseEntity
        {
            if (pagger.Sort.IsNullOrEmpty())
            {
                return entities.OrderByDescending(x => x.id);
            }
            else
            {
                var param = Expression.Parameter(typeof(TEntity));
                var prop = Expression.Property(param, pagger.Sort);
                var exp = Expression.Lambda(prop, param);
                string method;
                switch (pagger.SortType)
                {
                    case SortType.ASC: method = "OrderBy"; break;
                    case SortType.DESC:
                    default: method = "OrderByDescending"; break;
                }
                Type[] types = new Type[] { entities.ElementType, exp.Body.Type };
                var mce = Expression.Call(typeof(Queryable), method, types, entities.Expression, exp);
                return entities.Provider.CreateQuery<TEntity>(mce);
            }
        }
    }
}
